package cn.tit.ias.util.handlexcel;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelExportUtil_ {
	/**
	 * 
	 * @Title: exportExcel   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param tempPath 
	 * @param: @param path
	 * @param: @param response
	 * @param: @param list
	 * @param: @param exportWay  代表导出的类型   
	 * 0代表导出错误资产使用errorAssetInfo.xlsx模板  
	 * 1 代表导出资产信息使用assetInfo.xlsx模板  
	 * @return: void      
	 * @throws
	 */
	public void exportExcel(String tempPath, String path, HttpServletResponse response, List<Map<String, Object>> list,String exportWay) {
        // 读取excel模板，并复制到新文件中供写入和下载
		File newFile = createNewFile(tempPath, path);
        InputStream is = null;
        Workbook workbook = null;
        Sheet sheet = null;
        try {
        	// 将excel文件转为输入流
            is = new FileInputStream(newFile);
            // 创建个workbook，
            workbook = WorkbookFactory.create(is);
            // 获取第一个sheet
            sheet = workbook.getSheetAt(0);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        if (sheet != null) {
            try {
                // 写数据
                FileOutputStream fos = new FileOutputStream(newFile);
             // 填充数据
                if(exportWay.equals("0")){
                	createErrorTableRowValue(sheet,list);
                }else if(exportWay.equals("1")){
                	createAssetTableRowValue(sheet, list);
                }
                workbook.write(fos);
                fos.flush();
                fos.close();

                // 下载
                InputStream fis = new BufferedInputStream(new FileInputStream(
                        newFile));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                response.reset();
                response.setContentType("text/html;charset=UTF-8");
                OutputStream toClient = new BufferedOutputStream(
                        response.getOutputStream());
                response.setContentType("application/x-msdownload");
                String newName = URLEncoder.encode(
                        "Asset" + System.currentTimeMillis() + ".xlsx",
                        "UTF-8");
                response.addHeader("Content-Disposition",
                        "attachment;filename=\"" + newName + "\"");
                response.addHeader("Content-Length", "" + newFile.length());
                toClient.write(buffer);
                toClient.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 删除创建的新文件
        this.deleteFile(newFile);
    }
    public void exportAssetInfoExcel(String tempPath, String path, HttpServletResponse response, List<Map<String, Object>> list){
        // 读取excel模板，并复制到新文件中供写入和下载
		File newFile = createNewFile(tempPath, path);
        InputStream is = null;
        Workbook workbook = null;
        Sheet sheet = null;
        CellStyle cellStyle = null;  
        try {
        	// 将excel文件转为输入流
            is = new FileInputStream(newFile);
            // 创建个workbook，
            workbook = WorkbookFactory.create(is);
            cellStyle = workbook.createCellStyle(); 
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 
            // 获取第一个sheet
            sheet = workbook.getSheetAt(0);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (sheet != null) {
            try {
                // 写数据
                FileOutputStream fos = new FileOutputStream(newFile);
                // 填充数据
                createAssetTableRowValue(sheet, list);
                workbook.write(fos);
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 删除创建的新文件
        //this.deleteFile(newFile);
    }
	public void createErrorTableRowValue(Sheet sheet,List<Map<String, Object>> list){
		Row row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }
         Cell cell = row.getCell(0);
         if (cell == null) {
             cell = row.createCell(0);
         }
         //cell.setCellValue("我是标题");

         for (int i = 0; i < list.size(); i++) {
             Map<String, Object> vo = list.get(i);
             //从第二行开始
             row = sheet.createRow(i+1); 
             //根据excel模板格式写入数据....
             createRowAndCell(vo.get("imUnitName"), row, cell, 0);
             createRowAndCell(vo.get("imAssetRange"), row, cell, 1);
             createRowAndCell(vo.get("imDocumentNum"), row, cell, 2);
             createRowAndCell(vo.get("imAssetName"), row, cell, 3);
             createRowAndCell(vo.get("imAssetModel"), row, cell, 4);
             createRowAndCell(vo.get("imAssetPrice"), row, cell, 5);
             createRowAndCell(vo.get("imFactory"), row, cell, 6);
             createRowAndCell(vo.get("imBuyDate"), row, cell, 7);
             createRowAndCell(vo.get("imTakePeople"), row, cell, 8);
             createRowAndCell(vo.get("imRemark"), row, cell, 9);
             createRowAndCell(vo.get("imProfitLoss"), row, cell, 10);
         }
	}
	
	public void createAssetTableRowValue(Sheet sheet,List<Map<String, Object>> list){
		Row row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }
         Cell cell = row.getCell(0);
         if (cell == null) {
             cell = row.createCell(0);
         }
         //cell.setCellValue("我是标题");

         for (int i = 0; i < list.size(); i++) {
             Map<String, Object> vo = list.get(i);
             //从第二行开始
             row = sheet.createRow(i+1); 
             //根据excel模板格式写入数据....
             createRowAndCell(vo.get("depart"), row, cell, 0);
             createRowAndCell(vo.get("store"), row, cell, 1);
             createRowAndCell(vo.get("assetNum"), row, cell, 2);
             createRowAndCell(vo.get("assetName"), row, cell, 3);
             createRowAndCell(vo.get("assetModel"), row, cell, 4);
             createRowAndCell(vo.get("assetPrice"), row, cell, 5);
             createRowAndCell(vo.get("assetFactory"), row, cell, 6);
             createRowAndCell(vo.get("assetDocumentNum"), row, cell, 7);
             createRowAndCell(vo.get("assetBuyDate"), row, cell, 8);
             createRowAndCell(vo.get("assetTakePeople"), row, cell, 9);
             createRowAndCell(vo.get("assetRemrk"), row, cell, 10);
             createRowAndCell(vo.get("profitLoss"), row, cell, 11);
         }
	}
    /**
     *根据当前row行，来创建index标记的列数,并赋值数据
     */
    private void createRowAndCell(Object obj, Row row, Cell cell, int index) {
        cell = row.getCell(index);
        if (cell == null) {
            cell = row.createCell(index);
        }

        if (obj != null)
            cell.setCellValue(obj.toString());
        else 
            cell.setCellValue("");
    }

    /**
     * 复制文件
     * 
     * @param s
     *            源文件
     * @param t
     *            复制到的新文件
     */

    public void fileChannelCopy(File s, File t) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(s), 1024);
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取excel模板，并复制到新文件中供写入和下载
     * 
     * @return
     */
    public File createNewFile(String tempPath, String rPath) {
        // 读取模板，并赋值到新文件************************************************************
        // 文件模板路径
        String path = (tempPath);
        File file = new File(path);
        // 保存文件的路径
        String realPath = rPath;
        // 新的文件名
        String newFileName = System.currentTimeMillis() + ".xlsx";
        // 判断路径是否存在
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 写入到新的excel
        File newFile = new File(realPath, newFileName);
        try {
            newFile.createNewFile();
            // 复制模板到新文件
            fileChannelCopy(file, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFile;
    }

    /**
     * 下载成功后删除
     * 
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

}
